<?php

namespace app\admin\controller;

use think\Lang;
use think\Db;

class Order extends AdminControl
{

    const EXPORT_SIZE = 10000;

    public function _initialize()
    {
        parent::_initialize();
        Lang::load(APP_PATH . 'admin/lang/' . config('default_lang') . '/order.lang.php');
    }

    public function index()
    {
        $order_model = new \app\common\model\Order();
        $condition = array();
        $allinpay_state = $this->request->param('allinpay_state', 0, 'intval');
        $wms_state = $this->request->param('wms_state', 0, 'intval');
        $customs_state = $this->request->param('customs_state', 0, 'intval');
        $order_state = $this->request->param('order_state', '', 'trim');
        $order_sn = $this->request->param('order_sn', '', 'trim');
        $payment_code = $this->request->param('payment_code', '', 'trim');
        $buyer_name = $this->request->param('buyer_name', '', 'trim');
        $trade_mode = $this->request->param('trade_mode', 0, 'intval');
        $order_from = $this->request->param('order_from', 0, 'intval'); // 订单来源

        if (in_array($order_state, array('0', '10', '20', '30', '40'))) {
            $condition['order_state'] = $order_state;
        }
        $allinpay_state and $condition['allinpay_state'] = $allinpay_state;
        $wms_state and $condition['wms_state'] = $wms_state;
        $customs_state and $condition['customs_state'] = $customs_state;
        $order_sn and $condition['order_sn'] = $order_sn;
        $payment_code and $condition['payment_code'] = $payment_code;
        $buyer_name and $condition['buyer_name'] = $buyer_name;
        $trade_mode and $condition['trade_mode'] = $trade_mode;
        $order_from and $condition['order_from'] = $order_from; // 订单来源

        if(($customs_state == CUSTOMS_STATE_NOT_ISSUED || $wms_state == WMS_STATE_NOT_ISSUED || $wms_state == WMS_STATE_NOT_ISSUED) && $order_state === '') {
            // 未下发，查询已支付订单
            $condition['order_state'] = ['egt', ORDER_STATE_PAY];
        }

        $query_start_time = input('param.query_start_time');
        $query_end_time = input('param.query_end_time');
        $if_start_time = preg_match('/^20\d{2}-\d{2}-\d{2}$/', $query_start_time);
        $if_end_time = preg_match('/^20\d{2}-\d{2}-\d{2}$/', $query_end_time);
        $start_unixtime = $if_start_time ? strtotime($query_start_time) : null;
        $end_unixtime = $if_end_time ? strtotime($query_end_time) : null;
        if ($start_unixtime || $end_unixtime) {
            $condition['add_time'] = array('between', array($start_unixtime, $end_unixtime));
        }
        if($this->request->param('download', 0, 'intval')) {
            set_time_limit(0);
            $data = $order_model->getOrderList($condition,100, '*', 'order_id desc', self::EXPORT_SIZE, array('order_goods', 'order_common','member'));
            $this->createExcel($data);
        }
        $order_list = $order_model->getOrderList($condition, 15);
        $this->assign('show_page', $order_model->page_info->render());

        foreach ($order_list as $order_id => $order_info) {
            //显示取消订单
            $order_list[$order_id]['if_cancel'] = $order_model->getOrderOperateState('system_cancel', $order_info);
            //显示调整运费
            $order_list[$order_id]['if_modify_price'] = $order_model->getOrderOperateState('modify_price', $order_info);
            //显示收到货款
            $order_list[$order_id]['if_system_receive_pay'] = $order_model->getOrderOperateState('system_receive_pay', $order_info);
            //显示调整价格
            $order_list[$order_id]['if_spay_price'] = $order_model->getOrderOperateState('spay_price', $order_info);
            //显示发货状态
            $order_list[$order_id]['if_send'] = $order_model->getOrderOperateState('send', $order_info);
        }
        //显示支付接口列表(搜索)
        $payment_list = model('payment')->getPaymentOpenList();
        $this->assign('payment_list', $payment_list);
        $this->assign('order_list', $order_list);

        $this->assign('filtered', $condition ? 1 : 0); //是否有查询条件
        $this->setAdminCurItem('add');
        return $this->fetch();
    }

    /**
     * 线下订单
     * order_from 订单来源，1:PC 2:手机3:线下订单 固定是2
     */
    public function offline_order()
    {
        $this->request->get(['order_from' => 3]);
        return $this->index();
    }

    /**
     * 添加线下订单
     */
    public function create_offline_order()
    {
        if($this->request->isPost()) {
            halt($this->request->param());
        }
        $today = strtotime(date("Y-m-d"));
        $today = "159318";
        // $list = model('order')->where(["order_from"=>3,"add_time"=>[">=",$today]])->field("order_id,order_sn,buyer_id,buyer_name,order_amount,rcb_amount,pd_amount")->order("add_time desc")->select();
        $count = model('order')->where(["add_time"=>[">=",$today]])->count("order_id");
        $list = model('order')->where(["add_time"=>[">=",$today]])->field("order_id,order_sn,buyer_id,buyer_name,order_amount,rcb_amount,pd_amount")->order("add_time desc")->limit(15)->select();
        $this->assign([
            "list" => $list,
            "count" => $count,
        ]);
        return $this->fetch();
    }


    /**
     * 前端输入用户名或手机号获取用户信息
     */
    public function get_user_info_nameormobiel(){
        $rc_sn = $this->request->get('rc_sn');
        if ($rc_sn) {
            // 根据用户名手机号查询信息
            $member_info = model("member")->where(["member_id"=>$rc_sn])->field("")->find();
            if($member_info){
                return $this->success('', '', ['member_info' => $member_info]);
            }else{
                return $this->error('没有查询到对应的会员卡信息');
            }
        }
        return $this->fetch();
    }

    /**
     * 获取线下订单获取订单记录
     */
    public function get_order_history(){
        $page = input("param.page") <= 0 ? 1 : input("param.page");
        $page_num = !empty(input("param.page")) ? input("param.page") : 15;
        // $list = model('order')->where(["order_from"=>3])->field("order_id,order_sn,buyer_id,buyer_name,order_amount,rcb_amount,pd_amount")->limit(($page-1)*$page_num,$page_num)->order("add_time desc")->select();
        $list = model('order')->field("order_id,order_sn,buyer_id,buyer_name,order_amount,rcb_amount,pd_amount")->limit(($page-1)*$page_num,$page_num)->order("add_time desc")->select();

        $str = '';
        foreach ($list as $k => $v){
            $str .= '<tr class="shop-list" style="border: none;text-align: center"><td colspan="7" class="pl20" style="border: none;text-align: center"><p>
                <a href="javascript:top.scLayerOpen(\'/admin/order/show_order?order_id='.$v["order_id"].']\',\'查看订单-'.$v["order_sn"].'\')">'.$v["order_sn"].'</a>
                 </p><p style="margin-top: 3px">';
            if($v["buyer_id"]==10){
                $str .= '非会员';
            }else{
                $str .= '<a href="javascript:top.scLayerOpen(\'/admin/member/member?member_id\''.$v["buyer_name"].'\'])}\',\'查看会员-'.$v["buyer_name"].'\')">'.$v["buyer_name"].'</a>';
            }
            $str .= '</p></td><td colspan="7" class="pl20" style="border: none;text-align: center"><p>';
            if($v["pd_amount"]>0){
                $str .= '余额支付';
            }elseif($v["rcb_amount"]>0){
                $str .= '充值卡支付';
            }else{
                $str .= '第三方支付';
            }
            $str .= '</p><p style="margin-top: 3px">'.$v['order_amount'].'元</p></td></tr>';
        }


        return sc_json_encode(10000, "成功",$str);
    }

    /**
     * 线下订单中生成订单并结算
     */
    public function create_offline_order_pay(){
        if($this->request->isPost()){
            $param = input("post.");

            // 支付方式，默认为余额支付
            $param["pay_type"] = $param["pay_type"] < 1 ? 1 : $param["pay_type"];
            if(!in_array($param["pay_type"],[1,2,3,4])){
                return sc_json_encode(10001, "支付方式错误");
            }

            if($param["anonymous"] == "1") $param["member_id"]="10";

            // 验证信息不为空
            if(empty($param["member_id"])){
                return sc_json_encode(10001, '请填写用户信息');
            }
            if(empty($param["goods_id"]) || empty($param["num_input"])){
                return sc_json_encode(10001, '信息不全');
            }

            // 匿名支付
            if($param["member_id"]==10){
                if($param["pay_type"]==1 || $param["pay_type"]==2){
                    return sc_json_encode(10001, "非会员不能使用余额活充值卡");
                }
            }

            // 获取用户信息
            $member_model = model("member");
            $member_info = $member_model->getMemberInfoByID($param["member_id"]);
            if(!$member_info){
                return sc_json_encode(10001, "用户信息不存在");
            }
            if($member_info["is_buylimit"]==0 || $member_info["member_state"]==0){
                return sc_json_encode(10001, "用户未启用或无购买权限");
            }

            // 验证支付授权码
            if($param["pay_type"]==3 || $param["pay_type"]==4){
                if(!isset($param["authcode"]) || empty($param["authcode"])){
                    return sc_json_encode(10001, "支付授权码不存在");
                }
            }

            // 组合参数，将商品ID与数量放在一起
            $get_goods_info = [];
            $goods_ids = [];
            foreach ($param["goods_id"] as $k => $v) {
                $goods_ids[] = $v;
                $get_goods_info[$v]["id"] = $v;
                $get_goods_info[$v]["num"] = $param["num_input"]["$k"];
            }

            // 根据ID获取商品信息
            $goods_model = model("goods");
            $goods_info = $goods_model->getGoodsList(["goods_id"=>["in",$goods_ids]],"goods_id,goods_name,goods_commonid,goods_price,goods_image,goods_spec,goods_storage,goods_max_limit,goods_min_limit,gc_id");

            // 存储goods_commonid用于判断是否上架及锁定
            $goods_commonid = array_column($goods_info, "goods_commonid");
            // 商品公共列表，判断是否上架及锁定
            $goods_common_info = $goods_model->getGoodsCommonList(["goods_commonid"=>["in",$goods_commonid]],"goods_commonid,goods_name,goods_state,goods_lock");
            foreach ($goods_common_info as $comm_k => $comm_v){
                if($comm_v["goods_state"]!=1 || $comm_v["goods_lock"]!=0){
                    // 不符合条件的商品，给前台通知
                    return sc_json_encode(10001, "商品【".$comm_v["goods_name"]."】已下架或已锁定");
                }
            }

            $goods_info_sort = [];
            foreach ($goods_info as $k => $v){
                // 库存不足给前端通知
                if($v["goods_storage"]<$get_goods_info[$v["goods_id"]]["num"]){
                    return sc_json_encode(10001, "商品【".$v["goods_name"]."】库存不足，剩余：".$v["goods_storage"]);
                }
                // 购买限制
                if($v["goods_max_limit"]>0){
                    if($get_goods_info[$v["goods_id"]]["num"]<$v["goods_min_limit"] || $get_goods_info[$v["goods_id"]]["num"]>$v["goods_max_limit"]){
                        return sc_json_encode(10001, "商品【".$v["goods_name"]."】购买数量应在".$v["goods_min_limit"]."-".$v["goods_max_limit"]."之间");
                    }
                }
                // $goods_commonid[] = $v['goods_commonid'];
                $goods_info_sort[$v["goods_commonid"]][$v["goods_id"]] = $v;
                $goods_info_sort[$v["goods_commonid"]][$v["goods_id"]]["buy_nums"] = $get_goods_info[$v["goods_id"]]["num"];
            }

            // 通过的商品信息
            $goods_info_list = [];
            // 总金额
            $goods_total_price = 0;
            foreach ($goods_info_sort as $g_k => $g_v){
                foreach ($g_v as $k => $v){
                    $goods_total_price += bcmul($v["goods_price"],$v["buy_nums"],2);
                    $v["goods_total_price"] = bcmul($v["goods_price"],$v["buy_nums"],2);
                    $goods_info_list[] = $v;
                }
            }

            // 判断支付方式：余额、充值卡、通联
            if($param["pay_type"]==1){
                $deduct_filed = "available_predeposit";
                $balance = $member_info["available_predeposit"];
                $return_mes = "用户预存款余额不足";
            }elseif($param["pay_type"]==2){
                $deduct_filed = "available_rc_balance";
                $balance = $member_info["available_rc_balance"];
                $return_mes = "充值卡余额不足";
            }
            if($param["pay_type"]==1 || $param["pay_type"]==2){
                // 比较用户金额
                if(($balance*100)<$goods_total_price){
                    return sc_json_encode(10001,$return_mes );
                }
            }

            // 开启事务（防止其中一步失败）
            Db::startTrans();

            try {
                //订单信息
                // order模型
                $order_model = model("order");
                // 生成随机编号（订单编号）
                $pay_sn = makePaySn($member_info["member_id"]);

                $order_pay = [
                    "pay_sn" => $pay_sn,
                    "buyer_id" => $member_info["member_id"],
                    "api_paystate" => 1,
                ];
                // 生成支付订单信息
                $order_pay_id = $order_model->addOrderpay($order_pay);
                if (!$order_pay_id) {
                    Db::rollback();
                    return sc_json_encode(10001,"订单保存失败[未生成支付单]" );
                }
                $this->_logic_buy_1 = model('buy_1','logic');

                // 生成订单信息
                $data_order = [
                    "order_sn" => $this->_logic_buy_1->makeOrderSn($order_pay_id),
                    "pay_sn" => $pay_sn,
                    "order_buy_type" => 1,
                    "buyer_id" => $member_info["member_id"],
                    "buyer_name" => $member_info["member_name"],
                    // 没有卖家ID和名称
                    // "inviter_id" => "",
                    // "inviter_name" => "",
                    "buyer_email" => $member_info["member_email"],
                    "add_time" => time(),
                    "payment_code" => "online",
                    "order_state" => 40,
                    "order_amount" => $goods_total_price,
                    "goods_amount" => $goods_total_price,
                    "order_from" => 3,
                    // 订单税额
                    // "order_tax" => "",
                    // 发货类型
                    // "trade_mode" => "",
                ];
                if($param["pay_type"]==1){
                    $data_order["pd_amount"] = $goods_total_price;
                }elseif($param["pay_type"]==2){
                    $data_order["rcb_amount"] = $goods_total_price;
                }

                $res_order = $order_model->addOrder($data_order);
                if(!$res_order){
                    Db::rollback();
                    return sc_json_encode(10001,"订单生成失败" );
                }

                // 写入订单商品信息表
                $order_goods_data = [];
                foreach($goods_info_list as $g_k => $g_v){
                    $order_goods_data[$g_k] = [
                        "order_id" => $res_order,
                        "goods_id" => $g_v["goods_id"],
                        "goods_name" => $g_v["goods_name"],
                        "goods_spec" => implode(";",unserialize($g_v["goods_spec"])),
                        "goods_price" => $g_v["goods_price"],
                        "goods_num" => $g_v["buy_nums"],
                        "goods_image" => $g_v["goods_image"],
                        "goods_pay_price" => $g_v["goods_total_price"],
                        "buyer_id" => $member_info["member_id"],
                        "goods_type" => 1,
                        "gc_id" => $g_v["gc_id"],
                        "snapshot" => json_encode([     // 商品快照
                            'goods_info' => $goods_model->getGoodsInfoByID($g_v["goods_id"]),
                            'goods_common' => $goods_model->getGoodsCommonInfoByID($g_v['goods_commonid'])
                        ], JSON_UNESCAPED_UNICODE),
                    ];
                }

                $res_order_goods = $order_model->addOrdergoods($order_goods_data);
                if(!$res_order_goods){
                    Db::rollback();
                    return sc_json_encode(10001,"订单商品信息生成失败" );
                }

                // 用户更新数据(写入日志时修改了用户余额)
                // $member_up_data = [
                //     $deduct_filed => bcsub($balance,$goods_total_price,2),
                // ];
                // 写入积分日志 points_isuse开启积分机制 points_orderrate 消费额与赠送积分比例 points_ordermax 每单最多赠送积分
                // 获取配置
                $config = rkcache('config', true);
                if($config["points_isuse"] && $config["points_orderrate"]>0){
                    // 积分
                    $points = bcdiv($goods_total_price,$config["points_orderrate"],0);
                    if($points>0){
                        if($points>$config["points_ordermax"]) $points = $config["points_ordermax"];
                        // 积分表 pointslog 会员积分日志表 inviter_points_log 积分变更日志表
                        $pointslog_data = [
                            "pl_memberid" => $member_info["member_id"],
                            "pl_membername" => $member_info["member_name"],
                            "pl_points" => $points,
                            "pl_addtime" => time(),
                            "pl_desc" => "订单".$data_order["order_sn"]."购物消费",
                            "pl_stage" => "order",
                        ];
                        $res_points = model("points")->addPointslog($pointslog_data);
                        if(!$res_points){
                            Db::rollback();
                            return sc_json_encode(10001,"用户积分日志添加失败" );
                        }

                        // 添加用户积分
                        $res_member_up = $member_model->editMember(["member_id"=>$param["member_id"]],["member_points" => $member_info["member_points"]+$points]);
                        if(!$res_member_up){
                            Db::rollback();
                            return sc_json_encode(10001,"用户积分添加失败" );
                        }
                    }
                }

                // 记录扣费日志 支付方式
                if($param["pay_type"]==1){
                    // 余额
                    $pdlog_data = [
                        "member_id" => $member_info["member_id"],
                        "member_name" => $member_info["member_name"],
                        "order_sn" => $data_order["order_sn"],
                        "amount" => $goods_total_price,
                    ];
                    model("predeposit")->changePd("order_pay",$pdlog_data);
                }elseif($param["pay_type"]==2){
                    // 充值卡
                    $rcblog_data = [
                        "member_id" => $member_info["member_id"],
                        "member_name" => $member_info["member_name"],
                        "amount" => $goods_total_price,
                    ];
                    model("predeposit")->changeRcb("order_pay",$rcblog_data);
                }

                // 第三方支付接口
                if($param["pay_type"]==3 || $param["pay_type"]==4){
                    $pay_code = $param["pay_type"]==3 ? "allinpay" : "allinpay_h5";
                    $pay_info = model("payment")->where(["payment_code"=>$pay_code])->field("payment_code,payment_config")->find();
                    if(!$pay_info){
                        Db::rollback();
                        return sc_json_encode(10001,"暂无可用支付方式" );
                    }
                    // 请求第三方支付接口
                    $pay = new Pay();
                    // 用户交易数据(支付订单ID、金额、单号、支付授权码如微信,支付宝,银联的付款二维码)
                    $authcode = "";
                    $res_pay = $pay->pay(["pay_id"=>$order_pay_id,"amount"=>$goods_total_price,"order"=>$pay_sn,"authcode"=>$authcode],$pay_info["payment_code"]);
                    if($res_pay["code"]!=10000){
                        Db::rollback();
                        return sc_json_encode(10001,$res_pay["msg"]);
                    }
                }

                // 减少商品库存（销量及一些商品信息）
                $storage_sql = '`goods_storage` = CASE';
                $salenum_sql = '`goods_salenum` = CASE';
                $update_id = [];
                // 库存记录数据
                $data_storage = [];
                foreach ($goods_info_list as $k => $v) {
                    $storage_sql .= ' WHEN `goods_id`="'.$v['goods_id'].'" THEN `goods_storage`-'.$v['buy_nums'];
                    $salenum_sql .= ' WHEN `goods_id`="'.$v['goods_id'].'" THEN `goods_salenum`+'.$v['buy_nums'];
                    $update_id[] = $v["goods_id"];
                    $data_storage[] = [
                        "admin_id" => session("admin_id"),
                        "admin_name" => session("admin_name"),
                        "log_type" => 4,
                        "goods_name" => $v["goods_name"],
                        "goods_id" => $v["goods_id"],
                        "erp_storage" => -$v["buy_nums"],
                        "goods_storage" => $v["goods_storage"]-$v["buy_nums"],
                        "order_sn" => $data_order["order_sn"],
                        "content" => "用户【".$member_info["member_name"]."】支付成功,扣除库存",
                    ];
                }
                $storage_sql .= ' END, ';
                $salenum_sql .= ' END ';

                // 库存记录保存
                $res_storage = model("goodsStorageLog")->addStorageAll($data_storage);
                if(!$res_storage){
                    Db::rollback();
                    return sc_json_encode(10001,"库存记录写入失败" );
                }

                // 修改商品库存
                $res_reduce_stock = Db::execute('UPDATE sc_goods SET '.$storage_sql.$salenum_sql.' WHERE '.'goods_id in ('.implode(",",$update_id).')');
                if(!$res_reduce_stock){
                    Db::rollback();
                    return sc_json_encode(10001,"库存信息修改失败" );
                }

                Db::commit();
                return sc_json_encode(10000, '操作成功');
            }catch (\Exception $e){
                Db::rollback();
                return sc_json_encode(10001,$e->getMessage() );
            }
        }
    }

    /**
     * 查看订单
     */
    public function order_print()
    {
        $order_id = intval(input('param.order_id'));
        if ($order_id <= 0) {
            $this->error(lang('param_error'));
        }
        $order_model = model('order');
        $condition['order_id'] = $order_id;
        $order_info = $order_model->getOrderInfo($condition, array('order_common', 'order_goods'));
        if (empty($order_info)) {
            $this->error(lang('member_printorder_ordererror'));
        }
        $this->assign('order_info', $order_info);


        //订单商品
        $condition = array();
        $condition['order_id'] = $order_id;
        $goods_new_list = array();
        $goods_all_num = 0;
        $goods_total_price = 0;
        if (isset($order_info['extend_order_goods']) && !empty($order_info['extend_order_goods'])) {
            $i = 1;
            foreach ($order_info['extend_order_goods'] as $k => $v) {
                $v['goods_name'] = str_cut($v['goods_name'], 100);
                $goods_all_num += $v['goods_num'];
                $v['goods_all_price'] = sc_price_format($v['goods_num'] * $v['goods_price']);
                $goods_total_price += $v['goods_all_price'];
                $goods_new_list[ceil($i / 15)][$i] = $v;
                $i++;
            }
        }
        //优惠金额
        $promotion_amount = $goods_total_price - $order_info['goods_amount'];
        //运费
        $order_info['shipping_fee'] = $order_info['shipping_fee'];
        $this->assign('promotion_amount', $promotion_amount);
        $this->assign('goods_all_num', $goods_all_num);
        $this->assign('goods_total_price', sc_price_format($goods_total_price));
        $this->assign('goods_list', $goods_new_list);

        $this->setAdminCurItem();
        return $this->fetch('order_print');
    }

    /**
     * 平台订单状态操作
     *
     */
    public function change_state()
    {
        $order_id = intval(input('param.order_id'));
        if ($order_id <= 0) {
            $this->error(lang('miss_order_number'));
        }
        $order_model = model('order');

        //获取订单详细
        $condition = array();
        $condition['order_id'] = $order_id;
        $order_info = $order_model->getOrderInfo($condition, array('order_common', 'order_goods'));

        $state_type = input('param.type_state');

        // 撤回
        try {
            if ($state_type == 'cancel') {
                $result = $this->_order_cancel($order_info);
                if ($result['code']) {
                    sc_json_encode(10000, $result['msg']);
                }
            } elseif ($state_type == 'spay_price') {
                //修改商品价格
                $result = $this->_order_spay_price($order_info, input('post.'));
            } elseif ($state_type == 'modify_price') {
                //修改商品运费
                $result = $this->_order_ship_price($order_info, input('post.'));
            } elseif ($state_type == 'receive_pay') {
                $result = $this->_order_receive_pay($order_info, input('post.'));
            } elseif ($state_type == 'wms_state_refresh') {
                (new \app\common\model\Order())->editOrder([
                    'wms_state' => WMS_STATE_NOT_ISSUED,
                ], ['order_id' => $order_id]);
                sc_json_encode(10000, '操作成功');
            } elseif ($state_type == 'wms_state_undo') {
                \ordersync\OrderSync::WMSSyncRetract($order_info);
                (new \app\common\model\Order())->editOrder([
                    'wms_state' => WMS_STATE_NOT_ISSUED,
                ], ['order_id' => $order_id]);
                sc_json_encode(10000, '操作成功');
            } elseif ($state_type == 'customs_state_refresh') {
                (new \app\common\model\Order())->editOrder([
                    'customs_state' => CUSTOMS_STATE_NOT_ISSUED,
                ], ['order_id' => $order_id]);
                sc_json_encode(10000, '操作成功');
            } elseif ($state_type == 'allinpay_state_refresh') {
                (new \app\common\model\Order())->editOrder([
                    'allinpay_state' => ALLINPAY_STATE_NOT_ISSUED,
                ], ['order_id' => $order_id]);
                sc_json_encode(10000, '操作成功');
            } elseif ($state_type == 'platdata_upload_state_refresh') {
                (new \app\common\model\Order())->editOrder([
                    'platdata_upload_state' => PLATDATA_STATE_NEW,
                ], ['order_id' => $order_id]);
                \think\Db::name('platdataopen')->where(['order_no' => $order_info['order_sn']])->update([
                    'upload_state' => PLATDATA_STATE_NEW,
                    'update_time' => time(),
                ]);
                sc_json_encode(10000, '操作成功');
            }
            if (!$result['code']) {
                $this->error($result['msg']);
            } else {
                scLayerOpenSuccess($result['msg']);
            }
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
    }


    /**
     * 系统取消订单
     */
    private function _order_cancel($order_info)
    {
        $order_model = model('order');
        $logic_order = model('order', 'logic');
        $if_allow = $order_model->getOrderOperateState('system_cancel', $order_info);
        if (!$if_allow) {
            return sc_callback(false, '无权操作');
        }
        $result = $logic_order->changeOrderStateCancel($order_info, 'system', $this->admin_info['admin_name']);
        if ($result['code']) {
            $this->log(lang('order_log_cancel') . ',' . lang('order_number') . ':' . $order_info['order_sn'], 1);
        }
        return $result;
    }

    /**
     * 修改发货地址
     */
    private function _edit_order_daddress($daddress_id, $order_id)
    {
        $order_model = model('order');
        $data = array();
        $data['daddress_id'] = intval($daddress_id);
        $condition = array();
        $condition['order_id'] = $order_id;
        return $order_model->editOrdercommon($data, $condition);
    }

    /**
     * 修改商品价格
     * @param unknown $order_info
     */
    private function _order_spay_price($order_info, $post)
    {
        $order_model = model('order');
        $logic_order = model('order', 'logic');
        if (!request()->isPost()) {
            $this->assign('order_info', $order_info);
            $this->assign('order_id', $order_info['order_id']);
            echo $this->fetch('edit_spay_price');
            exit();
        } else {
            $if_allow = $order_model->getOrderOperateState('spay_price', $order_info);
            if (!$if_allow) {
                return sc_callback(false, '无权操作');
            }
            return $logic_order->changeOrderSpayPrice($order_info, 'admin', session('member_name'), $post['goods_amount']);
        }
    }

    /**
     * 修改运费
     * @param unknown $order_info
     */
    private function _order_ship_price($order_info, $post)
    {
        $order_model = model('order');
        $logic_order = model('order', 'logic');
        if (!request()->isPost()) {
            $this->assign('order_info', $order_info);
            $this->assign('order_id', $order_info['order_id']);
            echo $this->fetch('edit_price');
            exit();
        } else {
            $if_allow = $order_model->getOrderOperateState('modify_price', $order_info);
            if (!$if_allow) {
                return sc_callback(false, '无权操作');
            }
            return $logic_order->changeOrderShipPrice($order_info, 'admin', session('member_name'), $post['shipping_fee']);
        }
    }


    /**
     * 系统收到货款
     * @throws Exception
     */
    private function _order_receive_pay($order_info, $post)
    {
        $order_model = model('order');
        $logic_order = model('order', 'logic');
        $if_allow = $order_model->getOrderOperateState('system_receive_pay', $order_info);
        if (!$if_allow) {
            return sc_callback(false, '无权操作');
        }

        if (!request()->isPost()) {
            $this->assign('order_info', $order_info);
            //显示支付接口列表
            $payment_list = model('payment')->getPaymentOpenList();
            //去掉预存款和货到付款
            foreach ($payment_list as $key => $value) {
                if ($value['payment_code'] == 'predeposit' || $value['payment_code'] == 'offline') {
                    unset($payment_list[$key]);
                }
            }
            $this->assign('payment_list', $payment_list);
            $this->setAdminCurItem('receive_pay');
            echo $this->fetch('receive_pay');
            exit;
        } else {
            $order_list = $order_model->getOrderList(array('pay_sn' => $order_info['pay_sn'], 'order_state' => ORDER_STATE_NEW));
            $result = $logic_order->changeOrderReceivePay($order_list, 'system', $this->admin_info['admin_name'], $post);
            if ($result['code']) {
                $this->log('将订单改为已收款状态,' . lang('order_number') . ':' . $order_info['order_sn'], 1);
            }
            return $result;
        }
    }

    /**
     * 查看订单
     *
     */
    public function show_order()
    {
        $order_id = intval(input('param.order_id'));
        if ($order_id <= 0) {
            $this->error(lang('miss_order_number'));
        }
        $order_model = model('order');
        $order_info = $order_model->getOrderInfo(array('order_id' => $order_id), array('order_goods'));
        $order_info["extend_order_common"] = [];
        //订单变更日志
        $log_list = $order_model->getOrderlogList(array('order_id' => $order_info['order_id']));
        $this->assign('order_log', $log_list);

        //退款退货信息
        $refundreturn_model = model('refundreturn');
        $condition = array();
        $condition['order_id'] = $order_info['order_id'];
        $condition['admin_time'] = array('gt', 0);
        $return_list = $refundreturn_model->getReturnList($condition);
        $this->assign('return_list', $return_list);

        //退款信息
        $refund_list = $refundreturn_model->getRefundList($condition);
        $this->assign('refund_list', $refund_list);

        //卖家发货信息
        if (!empty($order_info['extend_order_common']['daddress_id'])) {
            $daddress_info = model('daddress')->getAddressInfo(array('daddress_id' => $order_info['extend_order_common']['daddress_id']));
            $this->assign('daddress_info', $daddress_info);
        }

        $this->assign('order_info', $order_info);
        return $this->fetch('show_order');
    }

    /**
     * 导出
     *
     */
    public function export_step1()
    {

        $order_model = model('order');
        $condition = array();
        $allinpay_state = $this->request->param('allinpay_state', 0, 'intval');
        $wms_state = $this->request->param('wms_state', 0, 'intval');
        $customs_state = $this->request->param('customs_state', 0, 'intval');
        $trade_mode = $this->request->param('trade_mode', 0, 'intval');

        $order_sn = input('param.order_sn');
        if ($order_sn) {
            $condition['a.order_sn'] = $order_sn;
        }
        $order_state = input('param.order_state');
        if (in_array($order_state, array('0', '10', '20', '30', '40'))) {
            $condition['a.order_state'] = $order_state;
        }
        $payment_code = input('param.payment_code');
        if ($payment_code) {
            $condition['a.payment_code'] = $payment_code;
        }
        $buyer_name = input('param.buyer_name');
        if ($buyer_name) {
            $condition['a.buyer_name'] = $buyer_name;
        }
        $allinpay_state and $condition['allinpay_state'] = $allinpay_state;
        $wms_state and $condition['wms_state'] = $wms_state;
        $customs_state and $condition['customs_state'] = $customs_state;
        $order_sn and $condition['order_sn'] = $order_sn;
        $payment_code and $condition['payment_code'] = $payment_code;
        $buyer_name and $condition['buyer_name'] = $buyer_name;
        $trade_mode and $condition['trade_mode'] = $trade_mode;

        if(($customs_state == CUSTOMS_STATE_NOT_ISSUED || $wms_state == WMS_STATE_NOT_ISSUED || $wms_state == WMS_STATE_NOT_ISSUED) && $order_state === '') {
            // 未下发，查询已支付订单
            $condition['order_state'] = ['egt', ORDER_STATE_PAY];
        }

        $query_start_time = input('param.query_start_time');
        $query_end_time = input('param.query_end_time');
        $if_start_time = preg_match('/^20\d{2}-\d{2}-\d{2}$/', $query_start_time);
        $if_end_time = preg_match('/^20\d{2}-\d{2}-\d{2}$/', $query_end_time);
        $start_unixtime = $if_start_time ? strtotime($query_start_time) : null;
        $end_unixtime = $if_end_time ? strtotime($query_end_time) : null;
        if ($start_unixtime || $end_unixtime) {
            $condition['a.add_time'] = array('between', array($start_unixtime, $end_unixtime));
        }

        if (!is_numeric(input('param.curpage'))) {
            $count = $order_model->getOrderCount($condition);
            $export_list = array();
            if ($count > self::EXPORT_SIZE) { //显示下载链接
                $page = ceil($count / self::EXPORT_SIZE);
                for ($i = 1; $i <= $page; $i++) {
                    $limit1 = ($i - 1) * self::EXPORT_SIZE + 1;
                    $limit2 = $i * self::EXPORT_SIZE > $count ? $count : $i * self::EXPORT_SIZE;
                    $export_list[$i] = $limit1 . ' ~ ' . $limit2;
                }
                $this->assign('export_list', $export_list);
                return $this->fetch('/public/excel');
            } else { //如果数量小，直接下载
                $data = $order_model->getOrderExcelList($condition, '', '*', 'a.order_id desc', self::EXPORT_SIZE);
                $this->createExcel($data);
            }
        } else { //下载
            $limit1 = (input('param.curpage') - 1) * self::EXPORT_SIZE;
            $limit2 = self::EXPORT_SIZE;
            $data = $order_model->getOrderExcelList($condition, '', '*', 'a.order_id desc', "{$limit1},{$limit2}");
            $this->createExcel($data);
        }
    }

    /**
     * 发货
     */
    public function send()
    {
        $order_id = input('param.order_id');
        if ($order_id <= 0) {
            $this->error(lang('param_error'));
        }

        $order_model = model('order');
        $condition = array();
        $condition['order_id'] = $order_id;
        $order_info = $order_model->getOrderInfo($condition, array('order_common', 'order_goods'));
        $if_allow_send = intval($order_info['lock_state']) || !in_array($order_info['order_state'], array(ORDER_STATE_PAY, ORDER_STATE_SEND));
        if ($if_allow_send) {
            $this->error(lang('param_error'));
        }

        if (!request()->isPost()) {
            $this->assign('order_info', $order_info);
            //取发货地址
            $daddress_model = model('daddress');
            $daddress_info = array();
            if ($order_info['extend_order_common']['daddress_id'] > 0) {
                $daddress_info = $daddress_model->getAddressInfo(array('daddress_id' => $order_info['extend_order_common']['daddress_id']));
            }
            if (empty($daddress_info)) {
                //取默认地址
                $daddress_info = $daddress_model->getAddressList(array(), '*', 'daddress_isdefault desc', 1);
                if (!empty($daddress_info)) {
                    $daddress_info = $daddress_info[0];
                    //写入发货地址编号
                    $this->_edit_order_daddress($daddress_info['daddress_id'], $order_id);
                } else {
                    //写入发货地址编号
                    $this->_edit_order_daddress(0, $order_id);
                }
            }
            $this->assign('daddress_info', $daddress_info);

            //如果是自提订单
            $express_list = rkcache('express', true);


            $this->assign('express_list', $express_list);

            return $this->fetch('send');
        } else {
            $logic_order = model('order', 'logic');
            $post = input('post.');
            $post['reciver_info'] = $this->_get_reciver_info();
            $result = $logic_order->changeOrderSend($order_info, 'admin', session('member_name'), $post);
            if (!$result['code']) {
                $this->error($result['msg']);
            } else {
                $this->success($result['msg'], url('order/index'));
            }
        }
    }

    /**
     * 生成excel
     *
     * @param array $data
     */
    private function createExcel($data = array())
    {
        Lang::load(APP_PATH . 'admin/lang/' . config('default_lang') . '/export.lang.php');
        $excel_obj = new \excel\Excel();
        $excel_data = array();
        //设置样式
        $excel_obj->setStyle(array('id' => 's_title', 'Font' => array('FontName' => '宋体', 'Size' => '12', 'Bold' => '1')));
        //header
        $excel_data[0][] = array('styleid' => 's_title', 'data' => lang('order_number'));
        $excel_data[0][] = array('styleid' => 's_title', 'data' => lang('buyer_name'));
        $excel_data[0][] = array('styleid' => 's_title', 'data' => lang('order_time'));
        $excel_data[0][] = array('styleid' => 's_title', 'data' => '订单总额');
        $excel_data[0][] = array('styleid' => 's_title', 'data' => lang('order_total_transport'));
        $excel_data[0][] = array('styleid' => 's_title', 'data' => lang('exp_od_paytype'));
        $excel_data[0][] = array('styleid' => 's_title', 'data' => lang('order_state'));
        $excel_data[0][] = array('styleid' => 's_title', 'data' => lang('exp_od_buyerid'));
        $excel_data[0][] = array('styleid' => 's_title', 'data' => lang('exp_od_bemail'));

        //订单用户信息
        $excel_data[0][] = array('styleid' => 's_title', 'data' => '卖家留言');
        $excel_data[0][] = array('styleid' => 's_title', 'data' => '收件人姓名');
        $excel_data[0][] = array('styleid' => 's_title', 'data' => '身份证');
        $excel_data[0][] = array('styleid' => 's_title', 'data' => '联系电话');
        $excel_data[0][] = array('styleid' => 's_title', 'data' => '省');
        $excel_data[0][] = array('styleid' => 's_title', 'data' => '市');
        $excel_data[0][] = array('styleid' => 's_title', 'data' => '区');

        //订单商品信息
        $excel_data[0][] = array('styleid' => 's_title', 'data' => '商品名称');
        $excel_data[0][] = array('styleid' => 's_title', 'data' => '商品单价');
        $excel_data[0][] = array('styleid' => 's_title', 'data' => '商品数量');
        $excel_data[0][] = array('styleid' => 's_title', 'data' => '商品总额');
        $excel_data[0][] = array('styleid' => 's_title', 'data' => '税金');


        $excel_data[0][] = array('styleid' => 's_title', 'data' => '万嘉仓库');
        $excel_data[0][] = array('styleid' => 's_title', 'data' => '单一窗口');
        $excel_data[0][] = array('styleid' => 's_title', 'data' => '通联支付单');
        $excel_data[0][] = array('styleid' => 's_title', 'data' => '海关179上报');

        //data
        foreach ((array)$data as $k => $v) {
            if(isset($v['extend_order_goods'])){
                foreach ($v['extend_order_goods'] as $key => $val){
                    $tmp = array();
                    if($key == 0){
                        $tmp[] = array('data' => 'DS' . $v['order_sn']);
                        $tmp[] = array('data' => $v['buyer_name']);
                        $tmp[] = array('data' => date('Y-m-d H:i:s', $v['add_time']));
                        $tmp[] = array('format' => 'Number', 'data' => sc_price_format($v['order_amount']));
                        $tmp[] = array('format' => 'Number', 'data' => sc_price_format($v['shipping_fee']));
                        $tmp[] = array('data' => get_order_payment_name($v['payment_code']));
                        $tmp[] = array('data' => get_order_state($v));
                        $tmp[] = array('data' => $v['buyer_id']);
                        $tmp[] = array('data' => $v['buyer_email']);
                        //订单收货信息
                        $tmp[] = array('data' => $v['extend_order_common']['deliver_explain']);
                        $tmp[] = array('data' => $v['extend_order_common']['reciver_name']);
                        if(!isset($v['extend_order_common']['reciver_info']['id_card_no'] )){
                            $tmp[] = array('data' => '');
                        }else{
                            $tmp[] = array('data' => $v['extend_order_common']['reciver_info']['id_card_no']);
                        }
                        $tmp[] = array('data' => $v['extend_order_common']['reciver_info']['mob_phone']);
                        $area = explode(' ',$v['extend_order_common']['reciver_info']['area']);
                        if(!$area || count($area)< 3){
                            $tmp[] = array('data' => '');
                            $tmp[] = array('data' => '');
                            $tmp[] = array('data' => '');
                        }else{
                            $tmp[] = array('data' => $area[0]);
                            $tmp[] = array('data' => $area[1]);
                            $tmp[] = array('data' => $area[2]);
                        }
                    }else{
                        $tmp[] = array('data' => '');
                        $tmp[] = array('data' => '');
                        $tmp[] = array('data' => '');
                        $tmp[] = array('data' => '');
                        $tmp[] = array('data' => '');
                        $tmp[] = array('data' => '');
                        $tmp[] = array('data' => '');
                        $tmp[] = array('data' => '');
                        $tmp[] = array('data' => '');
                        //订单收货信息
                        $tmp[] = array('data' => '');
                        $tmp[] = array('data' => '');
                        $tmp[] = array('data' => '');
                        $tmp[] = array('data' => '');
                        $tmp[] = array('data' => '');
                        $tmp[] = array('data' => '');
                        $tmp[] = array('data' => '');
                    }
                    //商品信息
                    $tmp[] = array('data' => $val['goods_name']);
                    $tmp[] = array('data' => $val['goods_price']);
                    $tmp[] = array('data' => $val['goods_num']);
                    $tmp[] = array('data' => number_format($val['goods_price']* $val['goods_num']),'2');
                    $tmp[] = array('data' => number_format(($val['goods_price']* $val['goods_info']['tax_rate'])/100,'2'));

                    $tmp[] = array('data' => dict_convert('wms_state',$v['wms_state']).$v['wms_msg']);
                    $tmp[] = array('data' => dict_convert('customs_state',$v['customs_state']).$v['customs_msg']);
                    $tmp[] = array('data' => dict_convert('allinpay_sync_state',$v['allinpay_state']).$v['allinpay_msg']);
                    $tmp[] = array('data' => dict_convert('platdata_upload_state',$v['platdata_upload_state']).$v['platdata_upload_msg']);
                    $excel_data[] = $tmp;
                }
            }
        }
        $excel_data = $excel_obj->charset($excel_data, CHARSET);
        $excel_obj->addArray($excel_data);
        $excel_obj->addWorksheet($excel_obj->charset(lang('sc_orders'), CHARSET));
        $excel_obj->generateXML($excel_obj->charset(lang('sc_orders'), CHARSET) . input('param.curpage') . '-' . date('Y-m-d-H', time()));
    }

}
